<template>
  <div class="app-container">
    <el-card class="toolbar-card" shadow="never">
      <div class="toolbar">
        <div class="toolbar-left">
          <el-button
            type="primary"
            icon="el-icon-caret-right"
            :disabled="jobList.length === 0 || allRunning"
            @click="handleStartAll"
          >开始所有任务</el-button>
          <el-button
            type="danger"
            icon="el-icon-square"
            :disabled="jobList.length === 0 || allStopped"
            @click="handleStopAll"
          >停止所有任务</el-button>
          <el-button
            type="success"
            icon="el-icon-video-play"
            :disabled="!hasSelection || selectedAllRunning"
            @click="handleStartSelected"
          >开始选中的任务</el-button>
          <el-button
            type="warning"
            icon="el-icon-video-pause"
            :disabled="!hasSelection || selectedAllStopped"
            @click="handleStopSelected"
          >停止选中的任务</el-button>
        </div>
      </div>
    </el-card>

    <el-table
      ref="jobTable"
      class="job-table"
      border
      v-loading="loading"
      :data="jobList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="70">
        <template slot-scope="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="任务名称" prop="jobName" min-width="160" />
      <el-table-column label="设备中继码" min-width="160">
        <template slot-scope="{ row }">
          {{ row.relayCode || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="任务组" prop="jobGroup" width="120" align="center" />
      <el-table-column label="执行计划" min-width="160" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.scheduleType === 'INTERVAL_MS'">{{ row.intervalMs }} ms</span>
          <span v-else>{{ row.cronExpression }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120" align="center">
        <template slot-scope="{ row }">
          <dict-tag :options="dict.type.sys_job_status" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" prop="updateTime" min-width="180" align="center" />
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button
            type="text"
            icon="el-icon-caret-right"
            :disabled="row.status === '0'"
            @click="handleStartRow(row)"
          >开始</el-button>
          <el-button
            type="text"
            icon="el-icon-circle-close"
            :disabled="row.status === '1'"
            @click="handleStopRow(row)"
          >停止</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { listJob, changeJobStatus } from '@/api/monitor/job'

const DEVICE_JOB_PATTERN = /^Device([1-9]|1[0-8])StatusPoll$/

export default {
  name: 'DataCollection',
  dicts: ['sys_job_status'],
  data() {
    return {
      loading: false,
      jobList: [],
      selectedRows: []
    }
  },
  computed: {
    hasSelection() {
      return this.selectedRows.length > 0
    },
    allRunning() {
      return this.jobList.length > 0 && this.jobList.every(item => item.status === '0')
    },
    allStopped() {
      return this.jobList.length > 0 && this.jobList.every(item => item.status === '1')
    },
    selectedAllRunning() {
      return this.hasSelection && this.selectedRows.every(item => item.status === '0')
    },
    selectedAllStopped() {
      return this.hasSelection && this.selectedRows.every(item => item.status === '1')
    }
  },
  created() {
    this.fetchJobList()
  },
  methods: {
    fetchJobList() {
      this.loading = true
      listJob({
        pageNum: 1,
        pageSize: 200,
        jobName: 'Device'
      }).then(response => {
        const rows = Array.isArray(response.rows) ? response.rows : []
        const jobs = rows
          .filter(item => DEVICE_JOB_PATTERN.test(item.jobName))
          .map(item => ({
            ...item,
            relayCode: this.extractRelayCode(item.invokeTarget)
          }))
          .sort((a, b) => this.getDeviceIndex(a.jobName) - this.getDeviceIndex(b.jobName))
        this.jobList = jobs
        this.$nextTick(() => {
          if (this.$refs.jobTable) {
            this.$refs.jobTable.clearSelection()
          }
        })
      }).finally(() => {
        this.loading = false
      })
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    handleStartRow(row) {
      this.confirmAndUpdate([row], '0', `确认要开始任务「${row.jobName}」吗？`)
    },
    handleStopRow(row) {
      this.confirmAndUpdate([row], '1', `确认要停止任务「${row.jobName}」吗？`)
    },
    handleStartAll() {
      this.confirmAndUpdate(this.jobList, '0', '确认要开始所有数据采集任务吗？')
    },
    handleStopAll() {
      this.confirmAndUpdate(this.jobList, '1', '确认要停止所有数据采集任务吗？')
    },
    handleStartSelected() {
      this.confirmAndUpdate(this.selectedRows, '0', '确认要开始选中的任务吗？')
    },
    handleStopSelected() {
      this.confirmAndUpdate(this.selectedRows, '1', '确认要停止选中的任务吗？')
    },
    confirmAndUpdate(rows, targetStatus, message) {
      const pendingRows = rows.filter(item => item.status !== targetStatus)
      if (pendingRows.length === 0) {
        this.$modal.msgWarning('当前选择的任务状态已符合要求')
        return
      }
      this.$modal.confirm(message).then(() => {
        this.batchUpdateStatus(pendingRows, targetStatus)
      }).catch(() => {})
    },
    async batchUpdateStatus(rows, targetStatus) {
      this.loading = true
      try {
        for (const item of rows) {
          await changeJobStatus(item.jobId, targetStatus)
        }
        this.$modal.msgSuccess('执行成功')
        this.fetchJobList()
      } catch (error) {
        console.error('批量更新任务状态失败', error)
        this.$modal.msgError('操作失败，请稍后重试')
        this.fetchJobList()
      }
    },
    extractRelayCode(invokeTarget) {
      if (!invokeTarget) {
        return ''
      }
      const match = invokeTarget.match(/getDeviceStatus\((?:'|")([^'")]+)(?:'|")\)/i)
      if (match && match[1]) {
        return match[1]
      }
      const genericMatch = invokeTarget.match(/"(.*?)"|'(.*?)'/)
      if (genericMatch) {
        return genericMatch[1] || genericMatch[2] || ''
      }
      return ''
    },
    getDeviceIndex(jobName) {
      const match = jobName.match(/Device(\d+)StatusPoll/)
      return match ? parseInt(match[1], 10) : Number.MAX_SAFE_INTEGER
    }
  }
}
</script>

<style scoped>
.toolbar-card {
  margin-bottom: 16px;
}

.toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.toolbar-left > .el-button + .el-button {
  margin-left: 8px;
}

.job-table {
  width: 100%;
}
</style>

